import {anyObj} from "@/core/indexDB/@type";
import { openConnect } from "@/core/indexDB/dataBase";

/**
 * 默认事务Promise方法
 * @param dataBaseName  数据库名称
 * @param tableList     表列表
 * @param cb            回调函数
 */
const transactionFn = ( dataBaseName:string,tableList:string[],cb = (objectStore:IDBObjectStore) => {} ) => {
    return new Promise(async (resolve, reject) => {
        const obj = await openConnect(dataBaseName, (event: any) => {
            const transaction = event?.transaction(tableList, 'readwrite')
            tableList.forEach(tableName => {
                const objectStore: IDBObjectStore = transaction.objectStore(tableName)
                cb(objectStore)
            })
        })
        resolve(obj)
    })

}



/**
 * 插入数据
 * @param dataBaseName 数据库名称
 * @param tableList 表列表
 * @param objectData
 */
export const insertData = ( dataBaseName:string,tableList:string[], objectData?:anyObj[]) =>
    transactionFn(dataBaseName,tableList, (objectStore) =>  {
    objectData?.forEach( data => {
        objectStore.add(data)
    })
})

/**
 *  修改数据
 * @param dataBaseName 数据库名称
 * @param tableList 数据表列表
 * @param updateData
 */
export const updateData = (dataBaseName:string, tableList:string[], updateData?:anyObj[] ) =>
    transactionFn(dataBaseName,tableList, (objectStore) =>  {
    updateData?.forEach( data => {
        objectStore.put(data)
    })
})

/**
 * 删除数据
 * @param dataBaseName 数据库名称
 * @param tableList    数据库表数组
 * @param key
 */
export const deleteData = ( dataBaseName:string,tableList:string[],key:any )  =>
    transactionFn(dataBaseName,tableList, (objectStore) =>
        objectStore.delete(key))


/**
 * 清空表数据
 * @param dataBaseName
 * @param tableList
 */
export const clearData = ( dataBaseName:string,tableList:string[] ) =>
    transactionFn(dataBaseName,tableList, (objectStore) =>
        objectStore.clear())